package com.superdry.utils;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.superdry.json.Userinfo;

import android.content.Context;

public class SPHelper {
	public static final String SP_NAME = "JM_Soldier";

	// TODO add new keys
	public static final String USERINFO = "userinfo";
	public static final String TOATAL_MONEY = "total_money";
	public static final long EMPTY_LONG_VALUE = -1;
	public static final String EMPTY_STRING_VALUE = "-1";
	public static final int EMPTY_INT_VALUE = 0;

	public static void putLong(Context context, String key, long in) {
		context.getSharedPreferences(SP_NAME, 0).edit().putLong(key, in).commit();
	}

	public static void putString(Context context, String key, String value) {
		context.getSharedPreferences(SP_NAME, 0).edit().putString(key, value).commit();
	}

	public static void putInt(Context context, String key, int value) {
		context.getSharedPreferences(SP_NAME, 0).edit().putInt(key, value).commit();
	}

	public static void putBoolean(Context context, String key, boolean value) {
		context.getSharedPreferences(SP_NAME, 0).edit().putBoolean(key, value).commit();
	}

	public static long getLong(Context context, String key) {
		return context.getSharedPreferences(SP_NAME, 0).getLong(key, EMPTY_LONG_VALUE);
	}

	public static String getString(Context context, String key) {
		return context.getSharedPreferences(SP_NAME, 0).getString(key, EMPTY_STRING_VALUE);
	}

	/**
	 * 得到用户信息
	 */
	public static Userinfo getUserInfo(Context context) {
		
		String json = context.getSharedPreferences(SP_NAME, 0).getString(USERINFO, EMPTY_STRING_VALUE);
		if(EMPTY_STRING_VALUE.equals(json)){
			return null;
		}
		List<Userinfo> info = null;
		try {
			info = JSON.parseArray(json, Userinfo.class);
		} catch (Exception e) {
			return JSON.parseObject(json, Userinfo.class);
		}
		return info.get(0);
	}

	public static int getInt(Context context, String key) {
		return context.getSharedPreferences(SP_NAME, 0).getInt(key, EMPTY_INT_VALUE);
	}

	public static boolean getBoolean(Context context, String key) {
		return context.getSharedPreferences(SP_NAME, 0).getBoolean(key, false);
	}

	public static void clearLong(Context context, String key) {
		putLong(context, key, EMPTY_LONG_VALUE);
	}

	public static void clearString(Context context, String key) {
		putString(context, key, EMPTY_STRING_VALUE);
	}

	public static void clearInt(Context context, String key) {
		putInt(context, key, EMPTY_INT_VALUE);
	}

	public static boolean containsLong(Context context, String key) {
		return (getLong(context, key) != EMPTY_LONG_VALUE);
	}

	public static boolean containsString(Context context, String key) {
		return !getString(context, key).equals(EMPTY_STRING_VALUE);
	}

	public static boolean containsInt(Context context, String key) {
		return (getInt(context, key) != EMPTY_INT_VALUE);
	}

}
